/**
 * MD5Encrypt.java
 * 
 * Create Version: 1.0
 * Author: 徐舟骏
 * Create Date: 2012-5-14
 */
package ysyh55.android.base.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * MD5Encrypt MD5加密类
 * 
 * @author 徐舟骏
 */
public class MD5Encrypt {
	public static String encryptPassword(String password) throws Exception {

		try {

			if (password != null && password.length() > 0) {
				return encodePassword(password, "MD5");

			} else {
				return "";
			}

		} catch (NoSuchAlgorithmException e) {
			throw e;
		}
	}

	private static String encodePassword(String _password, String _algorithm) throws NoSuchAlgorithmException {
		String password = _password;

		byte[] defaultBytes = password.getBytes();
		MessageDigest algorithm = MessageDigest.getInstance(_algorithm);
		algorithm.reset();
		algorithm.update(defaultBytes);
		byte messageDigest[] = algorithm.digest();

		StringBuffer hexString = new StringBuffer();
		for (int i = 0; i < messageDigest.length; i++) {

			String hex = Integer.toHexString(0xff & messageDigest[i]);
			if (hex.length() == 1) {
				hexString.append('0');
			}
			hexString.append(hex);
		}

		return hexString.toString();
	}
}
